import {EventEmitter, Injectable} from '@angular/core';
import {Observable} from "rxjs";
import Common from '../common/common';
import {ExtendHttpService} from "../services/extend-http.service";
import {Router} from "@angular/router";

@Injectable()
export class SocketService {
// WebSocket服务
  ws: WebSocket; // webSocket通信对象
  wsMessage = new EventEmitter(); // 向各个组件发射服务器传来的消息
  wsmsgstore: any; // 存储服务器发来的最新消息
  constructor(private extendHttp: ExtendHttpService,
              private router: Router) {
  }

// WebSocket服务连接
  wsConnect(loginAccount, loginPwd): Observable<any> {
    this.ws = new WebSocket(Common.socketDomain + '?login_account=' + loginAccount + '&login_pwd='
      + loginPwd + '&type=agentApp');
    return new Observable(
      observer => {
        this.ws.onmessage = (event) => {
          if (typeof event.data !== 'string') {
            let reader = new FileReader();
            reader.onload = (eve) => {
              observer.next(JSON.parse(eve['target']['result']));
            };
            reader.readAsText(event.data, 'utf-8');
          }
        };
        this.ws.onerror = (event) => {
          this.loginExit();
        };
        this.ws.onclose = (event) => {
          this.loginExit();
        }
      }
    );

  }

  // webSocket接收服务器发来的信息
  wsMsg(msg) {
    console.log(msg, '服务器新消息通知！');
    if (msg.code == '1502') {
      // this.router.navigate(['/login']);
      this.loginExit();
    }
    this.wsmsgstore = msg;
    this.wsMessage.emit(msg);
  }

  // WebSocket向服务器发送消息
  wsSendMessage(message: string) {
    this.ws.send(message);
  }

  // 抓取服务器发来的最新消息(信息流)
  wsGetMessage() {
    return new Observable(
      observer => {
        observer.next(this.wsmsgstore);
      }
    );
  }

  // webSocket关闭服务连接
  wsClose() {
    this.ws.close();
  }

  // 商家后台操作了用户以后退出
  loginExit() {
    this.extendHttp.get('/agentApp/login/exit', {}).subscribe(response => {
      let data = response.json();
      if (data.code == '0') {
        this.wsClose();
        this.router.navigate(['/login']);
      } else {

      }
    }, error => {
      this.router.navigate(['/login']);
    });
  }

}
